import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

print('----图一-----')
df = pd.read_csv("D:/data_1.csv")
V = df.iloc[0].values
mA = df.iloc[1].values
mW = df.iloc[2].values
plt.scatter(V, mA)
plt.plot(V, mA, color='red')
plt.title("Figure One")
plt.xlabel("Forward bias voltage/V")
plt.ylabel("Transmitter current/mA")
plt.savefig('C:/Users/admin/Desktop/图1.png', dpi=500, bbox_inches='tight')
plt.show()

print('----图二-----')
plt.scatter(mA, mW)
plt.plot(mA, mW, color='red')
k, b = np.polyfit(mA, mW, 1)
plt.plot(mA, k * mA + b, color='red')
print(f"方程为：y={k} * x - {-b}")
plt.title("Figure Two")
plt.xlabel("Transmitter current/mA")
plt.ylabel("Light power/mW")
plt.savefig('C:/Users/admin/Desktop/图2.png', dpi=500, bbox_inches='tight')
plt.show()

print('----图三-----')
df = pd.read_csv("D:/data_2.csv")
V = df.iloc[0].values
legend_list = ["P=0", "P=0.100mW", "P=0.200mW"]
for i in range(1, 4):
    uA = df.iloc[i].values
    plt.plot(V, uA, label=legend_list[i-1])
    plt.legend()
plt.title("Figure Three")
plt.xlabel("Reverse bias voltage/V")
plt.ylabel("Transmitter current/uA")
plt.savefig('C:/Users/admin/Desktop/图3.png', dpi=500, bbox_inches='tight')
plt.show()

print('----图四-----')
df = pd.read_csv("D:/data_3.csv")
angle = df.iloc[0].values
mW = df.iloc[1].values
mW_max = max(mW)
plt.plot(angle, mW)

y_target = mW_max / 2

for i in range(len(mW) - 1):
    y0, y1 = mW[i], mW[i + 1]
    x0, x1 = angle[i], angle[i + 1]

    # 检查是否跨越目标值
    if (y0 - y_target) * (y1 - y_target) < 0:
        # 线性插值计算交点
        t = (y_target - y0) / (y1 - y0)
        x_cross = x0 + t * (x1 - x0)
        plt.axvline(x=x_cross, color='gray', linestyle='--')
        plt.scatter(x_cross, y_target, color='red', s=50)  # 在最大值点上绘肯一个红色的圆点
        plt.annotate(f'half-value angle: \n({x_cross:.2f}, {y_target:.2f})', xy=(x_cross, y_target), xytext=(x_cross - 1, y_target + 0.5),
                     arrowprops=dict(facecolor='red', shrink=0.05))  # 添加注释，使用红色箭头连接注释和最大值点

plt.axhline(y=y_target, color='gray', linestyle='--')

plt.title("Figure Four")
plt.xlabel("angle/°")
plt.ylabel("Light power/mW")
plt.savefig('C:/Users/admin/Desktop/图4.png', dpi=500, bbox_inches='tight')
plt.show()

print('----题五-----')
df = pd.read_csv("D:/data_4.csv") * (10 ** -3)
I_0 = 5.06 * (10 ** -3)
df.insert(df.shape[1], '反射率', df.iloc[:, 2] / I_0)
df.insert(df.shape[1], '折射率', (1 + df.iloc[:, 3] ** 0.5) / (1 - df.iloc[:, 3] ** 0.5))
df.insert(df.shape[1], '衰减系数(/mm)', 2 ** -1 * np.log(I_0 / df.iloc[:, 1]))
print(f"{df.iloc[:, 3].T * 100 }\n{df.iloc[:, 4].T}\n{df.iloc[:, 5].T}")

print('----图六-----')
df = pd.read_csv("D:/data_5.csv")
U = df.iloc[0].values
T = df.iloc[1].values
T_max = max(T)
plt.plot(U, T)
threshold_T = T_max * 0.9
Turn_off_T = T_max * 0.1

for i in range(len(T) - 1):
    y0, y1 = T[i], T[i + 1]
    x0, x1 = U[i], U[i + 1]

    # 检查是否跨越目标值
    if (y0 - threshold_T) * (y1 - threshold_T) < 0:
        # 线性插值计算交点
        t = (threshold_T - y0) / (y1 - y0)
        x_cross = x0 + t * (x1 - x0)
        plt.axvline(x=x_cross, color='gray', linestyle='--')
        plt.scatter(x_cross, threshold_T, color='red', s=50)  # 在最大值点上绘肯一个红色的圆点
        plt.annotate(f'threshold_voltage: \n({x_cross:.2f}, {threshold_T:.2f})', xy=(x_cross, threshold_T), xytext=(x_cross - 1, threshold_T + 0.5),
                     arrowprops=dict(facecolor='red', shrink=0.05))  # 添加注释，使用红色箭头连接注释和最大值点

plt.axhline(y=threshold_T, color='gray', linestyle='--')

for i in range(len(T) - 1):
    y0, y1 = T[i], T[i + 1]
    x0, x1 = U[i], U[i + 1]

    # 检查是否跨越目标值
    if (y0 - Turn_off_T) * (y1 - Turn_off_T) < 0:
        # 线性插值计算交点
        t = (Turn_off_T - y0) / (y1 - y0)
        x_cross = x0 + t * (x1 - x0)
        plt.axvline(x=x_cross, color='gray', linestyle='--')
        plt.scatter(x_cross, Turn_off_T, color='red', s=50)  # 在最大值点上绘肯一个红色的圆点
        plt.annotate(f'turn-off_voltage: \n({x_cross:.2f}, {Turn_off_T:.2f})', xy=(x_cross, Turn_off_T), xytext=(x_cross - 1, Turn_off_T + 0.5),
                     arrowprops=dict(facecolor='red', shrink=0.05))  # 添加注释，使用红色箭头连接注释和最大值点

plt.axhline(y=Turn_off_T, color='gray', linestyle='--')

plt.title("Figure Six")
plt.xlabel("voltage/V")
plt.ylabel("transmittance(%)")
plt.savefig('C:/Users/admin/Desktop/图6.png', dpi=500, bbox_inches='tight')
plt.show()

print('----图七-----')
df = pd.read_csv("D:/data_6.csv")
angle = np.append(-df.iloc[1:, 4][:: -1], df.iloc[:, 0]) / 360 * 2 * np.pi  # 角度转弧度
T_max = np.append(df.iloc[1:, 5][:: -1], df.iloc[:, 1])
T_min = np.append(df.iloc[1:, 6][:: -1], df.iloc[:, 2])
T = T_max / T_min
print(T)
ax = plt.subplot(111, projection='polar')  # projection = 'polar' 指定为极坐标
ax.plot(angle, T, linewidth=3, color='red')  # 第一个参数为角度，第二个参数为极径
ax.grid(True)  # 是否有网格
ax.set_thetamax(90)
ax.set_thetamin(-90)
ax.set_theta_zero_location('N')
plt.savefig('C:/Users/admin/Desktop/图7.png', dpi=500, bbox_inches='tight')
plt.show()
